import 'package:flutter/material.dart';
import 'package:flutter_design/app/app_services.dart';
import 'package:flutter_design/modules/search/models/enable_model.dart';
import 'package:flutter_design/services/apis/api_paths.dart';
import 'package:flutter_design/utils/logger/logger.dart';
import '../../../app/environment_config.dart';
import '../../../services/http/api_exception.dart';
import '../../../services/http/http.dart';
import '../models/repo_model.dart';
import '../models/search_result_model.dart';

enum ViewState { idle, loading, success, error }

class SearchViewModel extends ChangeNotifier {
  // 1. 状态管理
  ViewState _state = ViewState.idle;
  ViewState get state => _state;

  List<Repo> _repos = [];
  List<Repo> get repos => _repos;

  String? _errorMessage;
  String? get errorMessage => _errorMessage;

  // 内部设置状态并通知监听者（View）
  void _setState(ViewState newState) {
    _state = newState;
    notifyListeners();
  }

  // 2. 业务逻辑
  Future<void> getEnv()async {
    try{
      final List<Enable> res = await Http.get<List<Enable>>(
        ApiPaths.enableApis,
        fromJsonT: (json){
          if(json is List){
            return json.map((item) => Enable.fromJson(item)).toList();
          }
          return [];
        }
      );

      // 2. 【核心逻辑】处理返回结果
      if (res.isNotEmpty) {
        // 列表不为空，获取第一项
        final firstEnable = res.first; // 使用 .first 更具可读性
        final newSuffix = firstEnable.url_prefix;
        await AppServices.cache.set("enable", newSuffix);
        // 健壮性检查：确保 url_prefix 不为空字符串
        if (newSuffix.isNotEmpty) {
          // 调用我们改造后的方法，传入获取到的前缀
          EnvironmentConfig.updateApiSuffix(newSuffix);
        } else {
          Logger.warn("getEnv", "Remote config item found, but its 'url_prefix' is empty. Suffix not updated.");
        }

        // 3. 【推荐修改】使用 forEach 进行日志打印
        // forEach 用于执行副作用（如打印日志）更安全、更明确。
        for (var i in res) {
          Logger.info("getEnv", "API Result Item: name=${i.name}, url_prefix=${i.url_prefix}");
        }

      } else {
        // 列表为空，打印警告日志，不执行任何更新操作
        Logger.warn("getEnv", "Received an empty list from remote config. Suffix not updated.");
      }
    }catch(e){
      Logger.error("getEnv", "is failed $e");
    }
  }


  Future<void> searchRepositories(String query) async {
    if (query.isEmpty) return;

    _setState(ViewState.loading);
    _errorMessage = null;

    try {
      // 使用你封装好的 Http 工具类发起请求
      final result = await Http.get<SearchResult>(
        ApiPaths.searchRepositories,
        queryParameters: {'q': query},
        // 关键：提供 fromJsonT 函数来解析数据
        fromJsonT: (json) => SearchResult.fromJson(json as Map<String, dynamic>),
      );

      _repos = result.items;
      _setState(ViewState.success);

    } on ApiException catch (e) {
      _errorMessage = e.message;
      _setState(ViewState.error);
      // 你可以在这里使用 PopupManager 显示一个弹窗
      // PopupManager.showErrorToast(e.message);
    } catch (e) {
      _errorMessage = "发生了一个未知错误";
      _setState(ViewState.error);
    }
  }
}